# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .MyIO import *
from .ConnFreeswitch import *
from .MySqlite import *

config_file_patch = "/usr/local/freeswitch/conf/"
getcwd="/var/www/MyIPPbx"
selectsql="select id,name,destination_number,effective_caller_id_number,sipname,sort from pbx_calloutextension ORDER BY sort"

class CallOutExtensionAdmin(object):
    list_display = ['name','destination_number','effective_caller_id_number', 'sipname','sort']
    list_per_page = 10
    add_form_template = 'myform.html'
    change_form_template = 'myform.html'
    search_fields = ['name', 'destination_number', 'effective_caller_id_number', 'sipname']

    def valid_forms(self):
        sipname = self.form_obj.data["sipname"]
        sipnum = ReadSql("select count(*) from pbx_sippro where name='"+sipname+"'")[0][0]
        if int(sipnum) == 0 :
            self.message_user(u'错误,未找到SIP别名，请先创建SIP网关', 'error')
        else:
            return self.form_obj.is_valid()

    def save_models(self):
        obj = self.new_obj
        #self.new_obj.save()
        urllist = str(self.request.get_full_path()).split('/')
        if len(urllist) == 5:
            sql = "INSERT INTO pbx_calloutextension(name, destination_number, effective_caller_id_number, sipname,sort) " \
                  "VALUES ('" + obj.name + "', '" + obj.destination_number.replace("d","\d") + "', '" + obj.effective_caller_id_number + "', '" + obj.sipname + "', '" + str(
                obj.sort) + "' )"
        else:
            sql="update pbx_calloutextension set destination_number='"+obj.destination_number.replace("d","\d")+"'," \
                "effective_caller_id_number='"+obj.effective_caller_id_number+"', sipname='"+obj.sipname+"'" \
                ",sort='"+str(obj.sort)+"' where id="+urllist[3]
        ComSql(sql)
        writeCallOut(selectsql)
        r = ReloadXml()
        if r == -1:
           self.message_user(u'告警,IPPBX加载失败，请重启IPPBX或者手动加载!', 'warning')
        #strsql = "select * from pbx_calloutextension where sipname='" + obj.sipname + "' ORDER BY id desc"
        #WriteCallOut(obj,strsql)
        # r = ReloadXml()

    def delete_models(self, obj):
        #deleteFile(obj, config_file_patch + "dialplan/default/", "_out.xml")
        obj.delete()
        writeCallOut(selectsql)
        r = Reloadacl()
        if r == -1:
            self.message_user(u'告警,IPPBX加载失败，请重启IPPBX或者手动加载!', 'warning')

def writeCallOut(strsql):
    info = ReadFile(os.path.join(getcwd + "/pbx/tpl", 'call_out.xml'))
    strcontent = ""
    aclList = ReadSql(strsql)
    for i in aclList:
        strcontent+=info.replace('{name}', i[1]).replace("{destination_number}",
                                                           i[2]).replace(
        "{effective_caller_id_number}", i[3]).replace('{sipname}', i[4]) + "\r\n"
    strcontent= "<include>\r\n"+strcontent+"<include>"
    WriteFile(config_file_patch + "dialplan/default/call_out.xml", strcontent)
